Skip to main content

Spring AI PromptTemplate

Banner Spring AI Icon

๐Ÿค– Mastering Spring AI Prompt Templatesโ€‹

๐ŸŽญ What's the Big Deal with Prompts?โ€‹

Imagine you're chatting with a super-intelligent AI, and all it takes to get a great response is how well you ask a question. Thatโ€™s what prompts are all about! In the realm of AGI (Artificial General Intelligence) and LLMs (Large Language Models), prompts are like magic spellsโ€”you craft them, and the AI conjures up an answer. ๐Ÿช„โœจ

Back in the day, prompts were just simple questions like: "Hey AI, what's up?" But now, with evolution (yes, AI evolves too!), they can differentiate between questions, instructions, and even philosophical dilemmas. ๐Ÿคฏ

This is where Spring AI PromptTemplate swoops in like a superhero to save us from bland prompts. Letโ€™s explore its wonders!


๐Ÿ“– Quick Reference Guide (Because Who Reads Long Docs?)โ€‹

String promptText = """
Tell about {topic} to a {age}-year-old person.
""";

//Get from user
String topic = "Black Hole";
int age = 14;

PromptTemplate promptTemplate = new PromptTemplate(promptText);
Message message = promptTemplate.createMessage(Map.of("topic", topic, "age", age));

Prompt prompt = new Prompt(List.of(message, message2, ...));
Generation generation = chatModel.call(prompt).getResult();

๐ŸŽฌ Step 1: Get to know Message and there typesโ€‹

message and their type

Note: getContent() is replaced with getText() as SpringAI is also evovling so you can understand that ๐Ÿ˜€


๐Ÿง Step 2: AI Roles โ€“ Whoโ€™s Who in the Conversation?โ€‹

Every good conversation has different personalities. In AI land, these are called roles:

ROLEAPI/ClassDescription
USERUserMessageThatโ€™s you! Asking the AI deep or silly questions.
ASSISTANTAssistantMessageThe AI answering your deep or silly questions.
SYSTEMSystemMessageThe secret boss behind the scenes, controlling how AI thinks. ๐Ÿง 
FUNCTIONFunctionMessageAIโ€™s external toolsโ€”like calling an API to fetch the latest cat memes. ๐Ÿฑ

๐ŸŽฎ Step 3: Talking to AI with Prompt APIโ€‹

Conversations with AI are managed through ModelRequest and ModelResponse. Itโ€™s like placing an order at a restaurant:

  • ModelRequest = What you ask the AI (your order)
  • ModelResponse = What the AI serves back (your meal ๐Ÿ”)

Example Code:

@GetMapping("/tourist/guide")
public String touristGuide(@RequestParam(value = "country", defaultValue = "India") String countryName) {
PromptTemplate pt = new PromptTemplate(promptUserMessageTemplate);
Prompt prompt = pt.create(Map.of("location", countryName));
return chatModel.call(prompt).getResult().getOutput().getText();
}

Output: provided Germany as input

Certainly! Here are five of Germany's most famous tourist spots, each accompanied by a brief description highlighting their uniqueness:

1. **Berlin**
The capital city is renowned for its rich cultural and historical landmarks, such as the iconic Brandenburg Gate symbolizing the Berlin Wall and the Reichstag building home to Germany's parliament.

2. **Munich**
Known as the "City of the Future," Munich boasts historic sites like the grand Schรถnbrunn Palace, vibrant nightlife, and the renowned Oktoberfest celebration in its old town.

3. **Stuttgart**
This city is celebrated for its musical heritage, home to the world's largest organ, along with its picturesque gardens and cultural museums.

4. **Hainaut Castle (Frankfurt)**
A historic fortress offering panoramic views of the surrounding landscape, it also features extensive gardens, making it a popular spot in Frankfurt am Main.

5. **Black Forest Park (Saarbrรผcken)**
Located near Saarbrรผcken, this park is a haven for nature enthusiasts with miles of hiking trails and the opportunity to visit ancient beech trees known as "Giant Trees."

Each destination offers a unique experience, from cultural exploration in Berlin to natural beauty in the Black Forest.

๐ŸŽจ Step 4: PromptTemplate API โ€“ The Picasso of AI Conversations ๐ŸŽจโ€‹

We donโ€™t always talk in plain sentences. Sometimes, we like to personalize our messages (like adding emojis! ๐Ÿ˜œ). Thatโ€™s where PromptTemplate comes in.

PromptTemplate promptTemplate = new PromptTemplate("Tell me about {subject}. Explain if I am {age} years old.");

//Obtain these values from user
String subject = "USA Elections";
int age = 14;

Prompt prompt = promptTemplate.create(Map.of("subject", subject, "age", age));
String output = chatModel
.call(prompt)
.getResult()
.getOutput()
.getText();

System.out.println(output);

๐Ÿ“ข Output:

Tell me about USA Elections. Explain if I am 14 years old.
USA Elections are the process where people in the United States choose who will be their leaders...

๐Ÿ† Step 5: Leveling Up โ€“ Combining Multiple Promptsโ€‹

What if multiple roles want to say something? No problem! Just stack โ€˜em up like a delicious AI sandwich. ๐Ÿฅช

@GetMapping("/tourist/guide/system")
public String touristGuideSystem(@RequestParam(value = "country", defaultValue = "India") String countryName) {
//Create Message with User messageType
PromptTemplate userPromptTemplate = new PromptTemplate(promptUserMessageTemplate);
Message userMessage = userPromptTemplate.createMessage(Map.of("location", countryName));

//Create Message with System messageType
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(promptSystemMessageTemplate);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Siri"));

//Create Prompt with both user and message
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
return chatModel.call(prompt).getResult().getOutput().getText();
}

Output: for input as India (generated response is greeting user then exiting statements are also nice)

Hello! Welcome to India, known for its vibrant culture and stunning landscapes! The country offers a rich variety of tourist spots that captivate visitors from around the world. Here are five must-visit destinations:

1. **Jaipur (Pink City)**: Renowned for its striking pink sandstone architecture, Jaipur is famous for the Amber Palace and Hawa Mahal, offering a serene retreat surrounded byhillside landscapes.

2. **Tajah Mahal**: Located in Agra near Delhi, this architectural marvel designed by Sir Edwin Landseer symbolizes love and reflects the intricate craftsmanship of Mughal art.

3. **Canals of Calcutta (Palghat Gap)**: Experience a blend of colonial charm and waterways with this network of canals that highlight Kolkata's history and culture.

4. **Western Ghats**: Known for their lush greenery, wildlife reserves like Bandhavgarh Tiger Reserve, and breathtaking hilltop views, these ranges are a haven for nature enthusiasts.

5. **Ooty Tea Plantations**: A picturesque hill station offering tea plantations, misty valleys, and serene gardens, perfect for a getaway with panoramic landscapes.

Thank you for considering India as your next destination!

Youn can checkout repo for DeepSeek AI where i have already provided reference implementation for you deepseek-ai using ollama


๐Ÿ“‚ Step 6: Keeping Things Organized โ€“ Injecting Template Strings as Resourcesโ€‹

If you donโ€™t want a cluttered Java file, store prompt templates separately! Just like separating your socks and shoes. ๐Ÿงฆ๐Ÿ‘Ÿ

/resources/prompts/system-message.stโ€‹

You are a helpful AI assistant named {name}.
Greet the user, summarize, then answer the request.
Always end with a thank-you message.

Java Codeโ€‹

@Value("classpath:/prompts/system-message.st")
private Resource promptSystemMessage;

SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Siri"));

๐ŸŽ‰ Step 7: Final Thoughts โ€“ AI Prompting Like a Proโ€‹

Weโ€™ve covered: โœ… Different roles in an AI convo โœ… How to craft dynamic prompts โœ… Using PromptTemplate like a boss โœ… Combining multiple prompts for epic AI responses โœ… Keeping things clean with resource files

๐Ÿ“ข Pro Tip: Play around with different prompt styles and see what wacky, wise, or wonderful responses you get!

๐Ÿ”— Want more? Check out LangChain4J Structured Output Example.

Happy Prompting! ๐Ÿš€๐ŸŽ‰